<?php

import('Psg.Notifier');
import('Psg.Core');
import('Psg.Messages');

function registrations() {
    if (PSG_CURUSRROLE != ("global" || "state")) {
        Url::redirect();
    }
    return [
        'performReg' => function() {
            $N = new Psg\Notifier();
            if (isset($_POST['btnAccept'])) {
                Psg\Core::registerUser($_POST['email']);
                $content = View::factory('_mail_regAcc');
            } else {
                Psg\Core::delRegistrationData($_POST['email']);
                $content = View::factory('_mail_regRef');
            }
            $N->Send([$_POST['email']], 'Rejestracja w Portalu PSG', $content);
            Url::redirect('administer/registrations');
        }
    ];
}

function messages() {
    return [
        'write' => function() {
            $from = $_POST['from'];
            $to = $_POST['to'];
            $topic = $_POST['topic'];
            $msg = $_POST['message'];
            Psg\Messages::writeMessage($from, $to, $topic, $msg);
            echo View::factory('rootTpl')
                    ->set('enableOSuccDlg', true);
        },
        'replyTo' => function() {
            echo View::factory('rootTpl')
                    ->set('content', 'messages_write')
                    ->set('viewParams', [$_POST['uid'], $_POST['topic']]);
        }
    ];
}

function settings() {
    return [
        'changeProfilePhoto' => function() {
            $plik_tmp = $_FILES['profilePhoto']['tmp_name'];

            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $ftype = finfo_file($finfo, $plik_tmp);
            finfo_close($finfo);
            $fcond = ($ftype == "image/jpeg" || $ftype == "image/png");

            if (is_uploaded_file($plik_tmp) && $fcond) {
                if ($ftype == "image/jpeg")
                    $image = imagecreatefromjpeg($plik_tmp);
                else
                    $image = imagecreatefrompng($plik_tmp);

                $uid = Psg\Core::getUserIdByMail(PSG_CURUSREMAIL);
                $newimage = imagecreatetruecolor(64, 64);
                list($w, $h) = getimagesize($plik_tmp);
                imagecopyresampled($newimage, $image, 0, 0, 0, 0, 64, 64, $w, $h);
                imagejpeg($newimage, DSF_DATADIR . DS . 'images' . DS . 'profile' . DS . $uid . '.jpg');
                imagedestroy($image);
                imagedestroy($newimage);
                echo View::factory('rootTpl')
                        ->set('content', 'settings_profile')
                        ->set('viewParams', 'success');
            } else {
                echo View::factory('rootTpl')
                        ->set('content', 'settings_profile')
                        ->set('viewParams', 'fail');
            }
        }
    ];
}